package com.xbaoziplus.simple_spring.beans.factory.support;

import com.xbaoziplus.simple_spring.beans.BeansException;
import com.xbaoziplus.simple_spring.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author xbaozi
 * @version 1.0
 * @classname SimpleInstantiationStrategy
 * @date 2023-04-20  20:05
 * @description JDK实例化策略
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        // 获取Class信息
        Class clazz = beanDefinition.getBeanClass();

        try {
            if (null != ctor) {
                // 如果ctor不为空，需要传递构造函数的入参信息进行实例化
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                // 如果ctor为空，则无构造器函数可实例化
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
